<template>
  <div class="app-container" >
    <!--main search body-->
    <div>
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
          <el-form-item label="关键字">
            <el-input
              v-model="queryParams.keyword"
              placeholder="请输入关键字"
              clearable
              size="small"
            />
          </el-form-item>
        </el-form>
        <!--main search button -->
        <div class="search-button">
            <el-button type="primary" icon="el-icon-search" size="mini" :loading="bannerLoding" @click="getList">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" :loading="bannerLoding" @click="resetSearch">重置</el-button>
        </div>

      </div>

      <div class="add-options">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="showAddReplyView"  v-hasPermi="['system:user:add']">新增</el-button>
      </div>
      <!-- main list body -->
      <el-table v-loading="bannerLoding" :data="replyList" :row-style="{'height':'90px'}" :stripe="true">
          <el-table-column label="关键字" align="center" prop="keyword"  width="120"/>
          <el-table-column label="回复类型" align="center" prop="mediaType" :show-overflow-tooltip="true"  width="120"/>
          <el-table-column label="回复文本内容" align="center" prop="text"  width="160" :show-overflow-tooltip="true"/>
          <el-table-column label="素材id" align="center" prop="mediaId"  width="160" :show-overflow-tooltip="true"/>
          <el-table-column label="素材url" align="center" prop="mediaUrl" width="160" :show-overflow-tooltip="true"/>
          <el-table-column label="视频/图文标题" align="center" prop="title" width="160" :show-overflow-tooltip="true"/>
          <el-table-column label="视频/图文描述" align="center" prop="description" :show-overflow-tooltip="true" width="160"/>
          <el-table-column label="图文图片" align="center" prop="picUrl" width="160" :show-overflow-tooltip="true"/>
          <el-table-column label="跳转链接" align="center"  prop="url" :show-overflow-tooltip="true" width="160"/>
          <el-table-column label="开始时间" align="center" prop="startTime" width="170"/>
          <el-table-column label="结束时间" align="center" prop="endTime" width="170"/>
          <el-table-column label="创建时间" align="center" prop="createTime" width="170"/>

          <!-- <el-table-column
            label="操作"
            align="center"
            width="180"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-dropdown @command="e=>handleCommand(e,scope)">
                <span class="el-dropdown-link">
                  操作<i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item v-if="!scope.row.skuState && scope.row.skuJdState" command="up">上架</el-dropdown-item>
                  <el-dropdown-item v-if="scope.row.skuState && scope.row.skuJdState" command="down">下架</el-dropdown-item>
                  <el-dropdown-item v-if="!scope.row.skuState  ||  !scope.row.skuJdState" command="del">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column> -->
      </el-table>

      <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.page"
          :limit.sync="queryParams.rows"
          @pagination="getList"
      />
      <el-dialog  title="新增回复消息" :visible.sync="showAddReplyDailog" width="900px" append-to-body>
         
        <div>
          <el-form :model="addReplyParams" ref="addReplyForm" :rules="rules" :inline="false" label-width="110px" v-loading="replyFormLoading">
            
            <el-form-item label="消息类型">
              <el-select v-model="addReplyParams.mediaType" class="reply-type-selector" placeholder="请选择" @change="onReplyTypeChanged">
                <el-option v-for="item in replyTypes" :key="item.code" :label="item.name" :value="item.code" />
              </el-select>     
            </el-form-item>

            <el-form-item label="消息有效时间" prop="replyValidTime">
              <el-date-picker
                format="yyyy 年 MM 月 dd 日"
                value-format="yyyy-MM-dd HH:mm:ss"
                :default-time="['00:00:00', '23:59:59']"
                v-model="addReplyParams.replyValidTime"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>

            <el-form-item label="关键字" prop="keyword">
              <el-input class="keyword-input" placeholder="请输入回复关键字" v-model="addReplyParams.keyword"/>
            </el-form-item>

            <el-form-item label="消息内容" prop="text" v-if="addReplyParams.mediaType == 'text'">
              <el-input class="keyword-input" placeholder="请输入消息内容" v-model="addReplyParams.text"/>
            </el-form-item>

            <el-form-item label="标题" prop="title" v-if="addReplyParams.mediaType == 'video' || addReplyParams.mediaType == 'news' ">
              <el-input class="keyword-input" placeholder="请输入标题" v-model="addReplyParams.title"/>
            </el-form-item>

            <el-form-item label="描述" prop="description">
              <el-input class="keyword-input" placeholder="请输入描述" v-model="addReplyParams.description"/>
            </el-form-item>

            <el-form-item label="图片链接" prop="picUrl" v-if="addReplyParams.mediaType == 'news'">
              <el-input class="keyword-input" placeholder="请输入图片链接" v-model="addReplyParams.picUrl"/>
            </el-form-item>

            <el-form-item label="跳转链接" prop="url" v-if="addReplyParams.mediaType == 'news'">
              <el-input class="keyword-input" placeholder="请输入跳转链接" v-model="addReplyParams.url"/>
            </el-form-item>

            <el-form-item label="添加素材" prop="mediaId" v-if="addReplyParams.mediaType == 'image' || addReplyParams.mediaType == 'video'">
              <el-radio v-model="addMediaMode" :label="0" @change="onAddMediaModeChange">上传素材</el-radio>
              <el-radio v-model="addMediaMode" :label="1" @change="onAddMediaModeChange">输入素材id</el-radio>
              <el-upload
                ref="upload"
                v-if="addMediaMode === 0"
                action=""
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :file-list="this.fileList"
                :auto-upload="false"
                :http-request="startUpload"
                :show-file-list="true"
                :limit="1"
                >
                <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
                <div slot="tip" class="el-upload__tip">{{this.fileLimit[addReplyParams.mediaType]}}</div>
              </el-upload>
              <div>
                <el-input class="keyword-input" v-if="addMediaMode === 1" placeholder="请输入素材id" v-model="addReplyParams.mediaId"/>
              </div>
              
            </el-form-item>

          </el-form>
        </div>

        <div slot="footer" class="dialog-footer">
          <el-button type="primary" :loading="replyFormLoading" @click="confirmAddReply('addReplyForm')">确 定</el-button>
        <el-button @click='cancelAddReply'>取 消</el-button>
        </div>
      </el-dialog>
  </div>
</template>

<script>

import {
  getReplyList,
  uploadMedia,
  addReply
} from "@/api/mall/replyApi";

export default {
  name: "ReplyManage",
  components: {

  },
  data() {
    return {
      replyList:[], //banner 列表
      total:0,
      bannerLoding:false,
      replyFormLoading: false,
      queryParams:{
        keyword: "",
        page: 1,
        rows: 10
      },
      showAddReplyDailog:false, //添加弹出框
      replyTypes:[
        {name:"文本消息",code:"text"},
        {name:"图片消息",code:"image"},
        {name:"视频消息",code:"video"},
        {name:"图文消息",code:"news"}
      ],
      fileLimit: {
        image: "支持bmp/png/jpeg/jpg/gif格式，且不超过10M",
        video: "支持MP4格式，且不超过10M"
      },
      // 新增回复参数
      addReplyParams: {},
      rules: {
          meidaType: [{ required: true, message: '请选择消息类型', trigger: 'change' }],
          keyword: [{ required: true, message: '请输入关键字', trigger: 'change' }],
          text: [{ required: true, message: '请输入回复内容', trigger: 'change' }],
          title: [{ required: true, message: '请输入标题', trigger: 'change' }],
          description: [{ required: true, message: '请输入描述', trigger: 'change' }],
          picUrl: [{ required: true, message: '请输入图片链接', trigger: 'change' }],
          url: [{ required: true, message: '请输入跳转链接', trigger: 'blur' }],
          replyValidTime: [{ type: 'array', required: true, message: '请选择回复有效期', trigger: 'change' }],
          mediaId: [{ required: true, message: '请上传文件到服务器', trigger: 'change' }]
      },
      addMediaMode: 1,
      fileList:[],
    };
  },

  created() {
    this.getList();
  },

  methods: {

   initAddReplyParams() {
     this.addReplyParams = {
        mediaType: "text",
        keyword: "",
        text: "",
        mediaId: "",
        mediaUrl: "",
        title: "",
        description: "",
        picUrl: "",
        url: "",
        replyValidTime: []
      }
   },
  
    // 点击新增,显示添加回复消息界面
    showAddReplyView(){
      // 初始化参数字段
      this.$refs.addReplyForm && this.$refs.addReplyForm.resetFields();
      this.initAddReplyParams();
      this.showAddReplyDailog = true;
      
    },

    // 获取回复消息列表
    getList() {
      this.bannerLoding = true;
      getReplyList(this.queryParams).then(response => {
          this.bannerLoding = false;
          if(response.code==200){
            console.log("消息列表结果 ---->", response);
            this.replyList = response.data.replyList;
            this.total = response.data.total;
          } else {
            this.$message("数据获取失败");
          }
        }
      );
    },

    resetSearch() {
      this.queryParams.keyword = "";
      this.getList();
    },

    submitUpload() {
      this.$refs.upload.submit();
    },

    handleRemove(file, fileList) {
      console.log("当前文件列表 --->",file,fileList);
      this.addReplyParams.mediaId = "";
      this.addReplyParams.mediaUrl = "";
    },

    handlePreview(file) {
      console.log(file);
    },

    startUpload(fileInfo) {
      this.replyFormLoading = true;
      console.log("上传的文件信息 -->", fileInfo);
      if (this.addReplyParams.mediaId != "") return alert("已经上传过该文件")
      var formData = new FormData();
      if (this.addReplyParams.mediaType == "video") {
        if (this.addReplyParams.title == null || this.addReplyParams.title == "") {
          return alert("请先填写视频标题和描述")
        } else {
          formData.append("title", this.addReplyParams.title);
          formData.append("description", this.addReplyParams.description);
        }
      }

      let fileName = fileInfo.file.name;
      let suffix = fileName.substring(fileName.lastIndexOf('.'));
      formData.append("mediaType", this.addReplyParams.mediaType);
      formData.append("suffix", suffix)
      formData.append("multipartFile", fileInfo.file);
      console.log("文件上传参数 -->",formData);

      uploadMedia(formData).then(res => {
        console.log("文件上传结果---->",res);
        this.replyFormLoading = false;
        if(res.code !== 200) return alert("文件上传失败");
        let data = res.data;
        if (undefined != data.mediaId) {
          this.addReplyParams.mediaId = data.mediaId;
        }

        if (undefined != data.mediaUrl && "" != data.mediaUrl) {
          this.addReplyParams.mediaUrl = data.mediaUrl;
        }
  
        // 手动校验表单数据
        this.$refs.addReplyForm.validateField("mediaId");
      })
    },

    // 确认添加回复消息
    confirmAddReply(formName) {
      this.replyFormLoading = true;
      console.log("当前回复消息的参数 --->", this.addReplyParams);
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let mediaType = this.addReplyParams.mediaType;
          if (mediaType == "" || mediaType == null) return alert("请选择消息类型");
          // if ((mediaType == "image" || mediaType == "video") && this.addReplyParams.mediaId == "") return alert("请先上传图片或视频");
          
          this.addReplyParams.startTime = this.addReplyParams.replyValidTime[0];
          this.addReplyParams.endTime = this.addReplyParams.replyValidTime[1];

          // 添加回复消息
          addReply(this.addReplyParams).then(res => {
            console.log("添加回复消息结果 ----->",res);
            if (res.code !== 200) return alert("添加回复消息失败");
            this.$alert('添加成功', '提示', {
              confirmButtonText: '确定',
              showClose: false,
              callback: action => {
                // 如果当前在第一页, 自动刷新复数据
                if (this.queryParams.page === 1) {
                  this.getList()
                }
              }
            });
            this.showAddReplyDailog = false;
            this.replyFormLoading = false;
          })
          
          console.log("当前回复消息的参数 --->", this.addReplyParams);
        } else {
          this.replyFormLoading = false;
          console.log('error submit!!');
          return false;
        }
      });
    },

    // 取消添加回复消息
    cancelAddReply() {
      this.showAddReplyDailog = false;
    },

    // 选择回复消息类型
    onReplyTypeChanged(value) {
      console.log('初始化媒体文件信息和表单校验信息');
      // 删除已上传的媒体文件信息
      this.addReplyParams.mediaId = "";
      this.addReplyParams.mediaUrl = "";
      this.$refs.addReplyForm.clearValidate();
    },

    // 切换添加素材的方式
    onAddMediaModeChange(value) {
      console.log("切换添加素材的方式 --->",value);
      this.addReplyParams.mediaId = "";
      this.addReplyParams.mediaUrl = "";
    }

  }
};
</script>

<style scoped>
  .search-button{
    display:flex;
    justify-content: center;
    margin-bottom: 10px;
  }
  .add-options{
    display: flex;
    justify-content: flex-end;
    margin-bottom: 10px;
    margin-right: 10px;
  }
  /* .el-input input{border:none;} */
  .reply-type-selector{
    width: 120px
  }

  .keyword-input {
    width: 400px;
  }

  .el-dropdown-link {
    cursor: pointer;
    color: #409EFF;
  }
</style>
